package br.com.netomarin.bundesliga.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import br.com.netomarin.bundesliga.model.MatchModel;
import br.com.netomarin.bundesliga.parser.MatchParser;
import br.com.netomarin.bundesliga.persistence.Match;

public class SpreadsheetLoaderServlet extends HttpServlet {

	private static final long serialVersionUID = 7305004918895353301L;

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		ServletFileUpload upload = new ServletFileUpload();
		FileItemIterator iter;
		FileItemStream item = null;
		
		try {
			iter = upload.getItemIterator(request);
			item = iter.next();
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		MatchParser.processMatchesCSV(item.openStream(), true);
		PrintWriter w = response.getWriter();
		w.write("<html><head><title>Jogos</title></head><body><h1>Jogos da Bundesliga</h1>");

		List<Match> matches = MatchModel.loadAllMatches();
		System.out.println("Total de partidas: " + matches.size());
		Iterator<Match> matchesIter = matches.iterator();
		for (int i = 0; matchesIter.hasNext(); i++) {
			Match m = matchesIter.next();
			w.write("Jogo #" + i + ": " + m.getHomeTeam() + " ("
					+ m.getHomeP1() + " / " + m.getHomeP2() + ") "
					+ m.getScoreHomeTeam() + " X " + m.getScoreVisitorTeam()
					+ m.getVisitorTeam() + " (" + m.getVisitorP1() + " / "
					+ m.getVisitorP2() + ")<br /> ");
		}

		w.write("</body></html>");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}
}